<?php

namespace DebugComponent\Formatter;

/**
 * Mask formatter for messages
 */
class Mask implements \DebugComponent\IFormatter {

    /**
     * Class constructor
     *
     * @param string $mask
     * @return Mask instance
     */
    public function __construct($mask) {
        $this->mask = $mask;
    }

    /**
     * Returns formatted message as string
     *
     * @param \DebugComponent\IMessage $message
     * @return string
     * @see \DebugComponent\IFormatter
     */
    public function format(\DebugComponent\IMessage $message) {
        list($year, $month, $day, $hour, $minute, $second) = explode('|', date('Y|m|d|H|i|s'));
        $result = str_replace(
                array('{message}', '{type}', '{year}', '{month}',
                    '{day}', '{hour}', '{minute}', '{second}'),
                array($message, $message->getType(), $year, $month,
                    $day, $hour, $minute, $second),
                $this->mask);
        if (strpos($result, '{message->') !== false) {
            $result = preg_replace('/\{message\->(?P<method>[a-zA-Z0-9_]+)\}/e', 'is_callable(array($message, "\1")) ? call_user_func(array($message, "\1")) : ""', $result);
        }
        return $result;
    }

    /**
     * @var string
     */
    private $mask;
}